from flask import Flask, jsonify, request
from flask_cors import CORS
import utils

app = Flask(__name__)
CORS(app)


def error404(error=None):
    return jsonify({
        "data": None,
        "status": 404,
        "msg": str(error)
    })


@app.route("/")
def index():
    return "Hello World!"

@app.route("/api/get_to_search", methods=['GET'])
def get_to_search():
    mysql = utils.MySQL(**utils.CONFIG)
    mysql.connect()
    try:
        shops = mysql.query("SELECT shop_id, shop_name FROM shop")
        dishes = mysql.query("SELECT dish_id, dish_name FROM dish")
        shop_dish = mysql.query("SELECT shop_id, dish_id FROM shop_dish")
    except Exception as e:
        return error404(e)
    finally:
        mysql.close()
    return jsonify({
        "data": {
            "shops": shops,
            "dishes": dishes,
            "shop_dish": shop_dish
        },
        "msg": "success",
        "status": 200
    }), 200

@app.route("/api/get_shop", methods=['GET'])
def get_shop():
    shop_id = request.args.get("shop_id")
    mysql = utils.MySQL(**utils.CONFIG)
    mysql.connect()
    try:
        shop_data = mysql.query(f"SELECT * FROM shop WHERE shop_id='{shop_id}'")[0]
        shop_dish = mysql.query(f"SELECT shop_id, dish_id FROM shop_dish WHERE shop_id='{shop_id}'")
        dish_data = []
        for i in shop_dish:
            dish_id = i['dish_id']
            dish_data_item = mysql.query(f"SELECT * FROM dish WHERE dish_id='{dish_id}'")[0]
            dish_data.append(dish_data_item)
    except Exception as e:
        return error404(e)
    finally:
        mysql.close()
    return jsonify({
        "data": {
            "shop_data": shop_data,
            "dish_data": dish_data
        },
        "msg": "success",
        "status": 200
    }), 200

@app.route("/api/get_nav", methods=['GET'])
def get_nav():
    _type = int(request.args.get("type"))
    mysql = utils.MySQL(**utils.CONFIG)
    mysql.connect()
    try:
        tag_shop = mysql.query("SELECT * FROM tag_shop")
        shop_ids = [i['shop_id'] for i in tag_shop if i['shopTag_id'] == _type]
        shop_data = []
        for shop_id in shop_ids:
            shop_item_data = mysql.query(f"SELECT * FROM shop WHERE shop_id={shop_id}")
            shop_data.append(shop_item_data[0])
    except Exception as e:
        return error404(e)
    finally:
        mysql.close()
    return jsonify({
        "data": {
            "shop_ids": shop_ids,
            "shop_data": shop_data
        },
        "status": 200,
        "msg": "ok"
    }), 200

@app.route('/api/get_top_shops', methods=["GET"])
def get_top_shops():
    page = int(request.args.get("page", 1))
    limit = int(request.args.get("limit", 10))
    offset = (page - 1) * limit
    mysql = utils.MySQL(**utils.CONFIG)
    mysql.connect()
    try:
        _data = mysql.query(f"SELECT * FROM shop ORDER BY "
                            f"shop_rating DESC, shop_sale_cnt DESC "
                            f"LIMIT {limit} OFFSET {offset}")
    except Exception as e:
        return error404(e)
    finally:
        mysql.close()
    return {
        "data": {"top": _data},
        "status": 200,
        "msg": "ok"
    }, 200

# 接口作用跟/api/get_shop 一样的...
@app.route('/api/get_cart_data', methods=["GET"])
def get_cart_data():
    try:
        shop_id = request.args.get("shop_id")
    except Exception as e:
        return jsonify({
            "data": None,
            "status": 400,
            "msg": "缺少参数shop_id"
        }), 400

    mysql = utils.MySQL(**utils.CONFIG)
    mysql.connect()

    try:
        shop_data = mysql.query("SELECT * FROM shop WHERE shop_id='{}'".format(shop_id))[0]
        dish_ids = mysql.query("SELECT dish_id FROM shop_dish WHERE shop_id='{}'".format(shop_id))
        dish_ids = [i['dish_id'] for i in dish_ids]
        dish_data = []
        for dish_id in dish_ids:
            dish_data_item = mysql.query(f"SELECT * FROM dish WHERE dish_id='{dish_id}'")[0]
            dish_data.append(dish_data_item)
    except Exception as e:
        return error404(e)
    finally:
        mysql.close()

    return jsonify({
        "data": {
            "shop_data": shop_data,
            "dish_data": dish_data
        },
        "status": 200,
        "msg": "ok"
    }), 200

if __name__ == "__main__":
    # mysql = utils.MySQL(**utils.CONFIG)
    # mysql.connect()
    # mysql.close()
    app.run(debug=True, port=8080)
